﻿using Daemon.Model;
using Microsoft.AspNetCore.Mvc;
using Daemon.Repository.Contract;
using System.Net.Http;
using Microsoft.AspNetCore.Http;
using Daemon.Common;
using Daemon.Service.Contract;
using System.Linq;

namespace DaemonAPI
{
	[ApiController]
	[Route("api/[controller]/[action]")]
	public class TakeAwayAccountTransactionController : BaseApiController<TakeAwayAccountTransaction, ITakeAwayAccountTransactionRepository>
	{
		private readonly ITakeAwayUserRepository _takeAwayUserRepository;

		public TakeAwayAccountTransactionController(ITakeAwayUserRepository takeAwayUserRepository, ITakeAwayAccountTransactionRepository repository, IHttpContextAccessor httpContextAccessor, ITakeAwayUserBookService takeAwayUserBookService) : base(repository, httpContextAccessor)
		{
			_takeAwayUserRepository = takeAwayUserRepository;
		}

		[HttpGet]
		[Route("")]
		public ResultModel<TakeAwayAccountTransaction, ITakeAwayAccountTransactionRepository> GetAllDetails(int userId)
		{
			var transactionList = _repository.FindAll().Where(r => r.UserId == userId).ToList();
			var userIds = transactionList.Select(r => r.UserId).ToList();
			var userInfos = _takeAwayUserRepository.FindAll().Where(r => userIds.Contains(r.Id)).ToDictionary(r => r.Id, r => r.UserName);
			transactionList.ForEach(item =>
			{
				if (userInfos.TryGetValue(item.UserId, out string name))
				{
					item.Description = string.Format(item.Description, name);
				}
			});

			return new ResultModel<TakeAwayAccountTransaction, ITakeAwayAccountTransactionRepository>(System.Net.HttpStatusCode.OK, null, transactionList);
		}

		[HttpGet]
		[Route("")]
		public ResultModel GetUserAccountInfo(int userId)
		{
			var userIntegeral = _repository.FindAll().Where(r => r.UserId == userId).Select(r => r.AdjustCost).ToList();
			if (!userIntegeral.Any())
			{
				return new ResultModel(System.Net.HttpStatusCode.OK, null, 0);
			}

			return new ResultModel(System.Net.HttpStatusCode.OK, null, userIntegeral.Sum());
		}
	}
}
